from flask import Blueprint, request, jsonify
from http import HTTPStatus
from app.models.analysis import AnalysisTask
from app.models.dataset import Dataset
from .services import AnalysisService

analysis_bp = Blueprint('analysis', __name__)

@analysis_bp.route('/analyze', methods=['POST'])
def create_analysis():
    """创建分析任务"""
    try:
        data = request.get_json()
        dataset_id = data.get('dataset_id')
        analysis_type = data.get('analysis_type')
        parameters = data.get('parameters', {})
        
        # 验证数据集是否存在
        dataset = Dataset.query.get(dataset_id)
        if not dataset:
            return jsonify({
                'error': f'Dataset not found: {dataset_id}'
            }), HTTPStatus.NOT_FOUND
            
        # 创建并执行分析任务
        task = AnalysisService.create_task(dataset_id, analysis_type, parameters)
        AnalysisService.execute_task(task)
        
        return jsonify({
            'message': 'Analysis task completed successfully',
            'task_id': task.id,
            'result': task.result
        }), HTTPStatus.CREATED
        
    except Exception as e:
        return jsonify({
            'error': str(e)
        }), HTTPStatus.BAD_REQUEST

@analysis_bp.route('/tasks/<int:task_id>', methods=['GET'])
def get_analysis_result(task_id):
    """获取分析任务结果"""
    try:
        task = AnalysisService.get_task(task_id)
        if not task:
            return jsonify({
                'error': f'Task not found: {task_id}'
            }), HTTPStatus.NOT_FOUND
            
        return jsonify({
            'task_id': task.id,
            'status': task.status,
            'result': task.result,
            'error_message': task.error_message
        })
    except Exception as e:
        return jsonify({
            'error': str(e)
        }), HTTPStatus.BAD_REQUEST

bp = analysis_bp 